package com.workflow.listener;

import com.gec.domain.Role;
import com.gec.domain.User;
import com.gec.service.abst.LeaveService;
import com.gec.utils.MyWebUtils;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;

public class LeaveTaskHandler implements TaskListener {

    private final LeaveService leaveService;

    public LeaveTaskHandler() {
        //{ps}在这里装配 leaveService.
        leaveService = MyWebUtils.getBean(LeaveService.class);
    }

    @Override
    public void notify(DelegateTask task) {
        //{1}获取 HttpSession 中的用户
        User user = MyWebUtils.getCurrentUser();
        //{2}获取流程实例ID, 任务ID
        String insID = task.getProcessInstanceId();
        String taskID = task.getId();
        //{3}获取当前用户角色名称 [主要角色]
        Role priRole = user.getPrimaryRole();
        String roleName = priRole.getRoleName();

        String assignee;
        String deptId = user.getDept().getId();
        System.out.println("+---------------------------------------------------+");
        System.out.println(priRole);
        System.out.println(roleName);
        System.out.println(deptId);



        System.out.println("+---------------------------------------------------+");

        if ("employee".equals(roleName)) {
            //4.1-情况一: 你是员工
            //4.2-获取你当前部门的领导的 user.id
            assignee = leaveService.getDeptLeader(deptId);
        } else if ("leader".equals(roleName)) {
            //4.2-情况二: 你是 Leader, 获取上一级部门领导id
            assignee = leaveService.getHigherDeptLeader(
                    deptId);
        } else {
            throw new RuntimeException("找不到办理人。");
        }
        //4. 设置办理人
        task.setAssignee(assignee);
        //5. 保存 leave 信息到 t_leave 表。
        leaveService.updateAssigneeAndTask(insID, taskID, assignee);
    }

}
